import React, { useState, useEffect } from 'react';
import { connect } from 'dva';
import { List, Tabs, Card, Row, Col, Button, Space, Typography, Pagination, Input } from 'antd';
import { StarOutlined, LikeOutlined, MessageOutlined, FieldTimeOutlined, DislikeOutlined, EyeOutlined } from '@ant-design/icons';
import { history } from 'umi';
const { Paragraph } = Typography;
const IconText = ({ icon, text }) => (
  <Space>
    {React.createElement(icon)}
    {text}
  </Space>
);
const HomePage = ({ categoryList, tagList, articleList, dispatch, userInfo, total }) => {
  const [dataSource, setDataSource] = useState([])
  const [tagId, setTagId] = useState('0');
  const [categoryId, setCategoryId] = useState('0');
  const [value, setValue] = useState('');
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  useEffect(() => {
    if (tagList.filter(tag => tag.tagId === tagId).length === 0) {
      setTagId('0');
    }
    setDataSource([{ key: '0', table: '全部' }, ...tagList.map((item, index) => ({ key: item.tagId, table: item.tagName }))])
  }, [tagList])
  const categoryItems = [
    { key: '0', label: '全部' }, ...categoryList.map(item => ({ key: item.categoryId, label: item.categoryName })),
  ];
  const handleButtonClick = (tagId) => {
    setTagId(tagId);
    setPage(1);
    dispatch({
      type: 'homePage/queryAllArticle',
      payload: {
        tagId: tagId,
        categoryId: categoryId,
        userId: userInfo.userId,
        page: 1,
        pageSize: pageSize,
      }
    })
  };
  const onChange = (key) => {
    setPage(1);
    setCategoryId(key);
    dispatch({
      type: 'homePage/queryTag',
      payload: {
        categoryId: key,
      }
    })
    dispatch({
      type: 'homePage/queryAllArticle',
      payload: {
        tagId: tagId,
        categoryId: key,
        userId: userInfo.userId,
        page: 1,
        pageSize: pageSize,
      }
    })
  };
  const handlPage = (page, pageSize) => {
    setPage(page);
    setPageSize(pageSize);
    if (value.length > 0) {
      dispatch({
        type: 'homePage/queryArticles',
        payload: {
          keyWords: value,
          userId: userInfo.userId,
        }
      })
    }
    else {
      dispatch({
        type: 'homePage/queryAllArticle',
        payload: {
          tagId: tagId,
          categoryId: categoryId,
          userId: userInfo.userId,
          page: page,
          pageSize: pageSize,
        }
      })
    }
  }
  const onSearch = (value) => {
    setPage(1);
    setValue(value);
    dispatch({
      type: 'homePage/queryArticles',
      payload: {
        keyWords: value,
        userId: userInfo.userId,
        page: 1,
        pageSize: pageSize,
      }
    })
  };
  return (<>

    <Card style={{ height: '90px', position: 'relative' }}>
      <div style={{
        position: 'absolute',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        backgroundImage: `url(/image/login/homepage.jpg)`,
        backgroundSize: 'cover',
        backgroundPosition: 'center',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center'
      }}>
        <Input.Search style={{ width: '400px', borderRadius: '20px' }} onSearch={onSearch} placeholder="请输入搜索内容" enterButton />
      </div>
    </Card>
    <Card>
      <Row>
        <Col span={20} offset={2}>
          <Tabs defaultActiveKey="0" items={categoryItems} onChange={onChange} tabPosition={'top'}/>
          <List
            grid={{ gutter: 16 }}
            dataSource={dataSource}
            renderItem={(item, index) => (
              <List.Item key={index}>
                <Button
                  type="text"
                  size="small"
                  onClick={() => handleButtonClick(item.key)}
                  style={{
                    backgroundColor: tagId === item.key ? '#433939' : 'transparent',
                    color: tagId === item.key ? '#fff' : '#433939',
                    borderRadius: '20px',
                  }}
                >{item.table}
                </Button>
              </List.Item>
            )}
          />
        </Col></Row>
    </Card>
    <Row><Col span={18} offset={2}>
      <List
        size="small"
        dataSource={articleList === null ? [] : articleList}
        renderItem={(item) => (
          <List.Item key={item.articleId}>
            <Card hoverable style={{ width: '100%', borderRadius: 10 }} onClick={() => { 
              history.push({ pathname: '/homePage/articleDetail', state: { articleId: item.articleId } }) 
              dispatch({
                  type: 'homePage/viewArticle',
                  payload: {
                    articleId: item.articleId,
                  }
              })
              }}>
              <Card.Meta title={item.title} description={<Paragraph ellipsis={true}>{item.content.replace(/<[^>]*>?/gm, '')}</Paragraph>} />
              <Row>
                <Col span={2}><IconText icon={StarOutlined} text={item.collectCount} key="list-vertical-star-o" /></Col>
                <Col span={2} offset={1}><IconText icon={EyeOutlined} text={item.view} key="list-vertical-eye" /></Col>
                <Col span={2} offset={1}><IconText icon={LikeOutlined} text={item.like} key="list-vertical-like-o" /></Col>
                <Col span={2} offset={1}><IconText icon={DislikeOutlined} text={item.disLike} key="list-vertical-dislike-o" /></Col>
                <Col span={2} offset={1}><IconText icon={MessageOutlined} text={item.commentCount} key="list-vertical-message" /></Col>
                <Col span={4} offset={1}><IconText icon={FieldTimeOutlined} text={item.updateTime} key="list-vertical-updateTime" /></Col>
              </Row>
            </Card>
          </List.Item>
        )}
      />
      <br />
    </Col>
      <Col span={18} offset={3} style={{ textAlign: 'center' }} ><Pagination showQuickJumper showSizeChanger current={page} total={total} onChange={handlPage} /></Col>
    </Row>
    <br />
  </>);
};

export default connect(({ homePage, user }) => ({
  categoryList: homePage.categoryList,
  tagList: homePage.tagList,
  articleList: homePage.articleList,
  userInfo: user.userInfo,
  total: homePage.total,
}))(HomePage);